package ru.pstu.itas.cps.controls;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;

public class Arm extends ActiveElement implements Touchable {

	int min_value;
	int max_value;
	int length;
	int radius;
	Bitmap img;
	int std_value;
	boolean draging = false;
	float armX;
	float armY;

	public Arm(String id, int x, int y, int value, int min_value, int max_value, int length, int radius,
			Bitmap img) {
		super(id, x, y, value);
		this.min_value = min_value;
		this.max_value = max_value;
		this.length = length;
		this.radius = radius;
		this.img = img;
		this.std_value = value;
	}

	public void TouchDown(float x, float y) {
		if ((x - armX) * (x - armX) + (y - armY) * (y - armY) < radius * radius) {
			draging = true;
		} else {
			draging = false;
		}
	}

	public void TouchMove(float x, float y) {
		float dist = (x - armX) * (x - armX) + (y - armY) * (y - armY); 
		if (dist < radius * radius)
			draging = true;
		if (dist > 2 * radius * radius) {
			draging = false;
			setValue(std_value);
		}
		if (draging) {
			int newValue = (int) Math.round(Math.atan((y - this.y) / (x - this.x)) * 180 / Math.PI);
			if (newValue < min_value)
				newValue = min_value;
			else if (newValue > max_value)
				newValue = max_value;
			setValue(newValue);
		}
	}

	public void TouchUp(float x, float y) {
		draging = false;
		setValue(std_value);
	}

	@Override
	public void Draw(Canvas canvas) {
		Matrix mtx = new Matrix();
		mtx.postRotate(value);
		Bitmap i = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), mtx, true);
		Rect srcRect = new Rect(0, 0, i.getWidth(), i.getHeight());
		Rect dstRect = new Rect(x - i.getWidth() / 2, y - i.getHeight() / 2, x + i.getWidth() / 2, y
				+ i.getHeight() / 2);
		canvas.drawBitmap(i, srcRect, dstRect, null);
	}
	
	@Override
	public void setValue(int value) {
		super.setValue(value);
		armX = (float) (this.x + length * Math.cos(value * Math.PI / 180));
		armY = (float) (this.y + length * Math.sin(value * Math.PI / 180));
	}

}
